package com.ueip.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ueip.backend.mapper.UserInfoMapper;
import com.ueip.backend.mapper.UserMapper;
import com.ueip.backend.pojo.User;
import com.ueip.backend.pojo.UserInfo;
import com.ueip.backend.service.UserInfoService;
import com.ueip.backend.service.UserService;
import com.ueip.backend.service.impl.utils.UserDetailsImpl;
import com.ueip.backend.utils.IdentityAuthenticationUtil;
import com.ueip.backend.utils.JwtUtil;
import com.ueip.backend.vo.Result;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public Result add(Map<String, String> data) {
        IdentityAuthenticationUtil.getCurUser();
        String username = data.get("username");
        String password = data.get("password");

        if (username == null || username.length() == 0) {
            return Result.error("用户名不能为空");
        }
        if (username.length() > 50) {
            return Result.error("用户名过长");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<User> users = userMapper.selectList(queryWrapper);
        if (!users.isEmpty()) {
            return Result.error("用户名已存在");
        }
        userMapper.insert(new User(null, username, password));
        return Result.ok("success");
    }

    @Override
    public Result deleteById(Map<String, String> data) {
        IdentityAuthenticationUtil.getCurUser();
        try {
            Integer id = Integer.parseInt(data.get("id"));
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("id", id);
            List<User> users = userMapper.selectList(userQueryWrapper);
            if (users.isEmpty()) {
                return Result.error("该用户不存在或已被删除");
            }
            userMapper.deleteById(id);
        } catch (Exception e) {
            return Result.error("id类型有误");
        }
        return Result.ok("success");
    }

    @Override
    public Result getAll() {
        IdentityAuthenticationUtil.getCurUser();
        return Result.ok(userMapper.selectList(null));
    }

    @Override
    public Result login(Map<String, String> data) {
        String username = data.get("username");
        String password = data.get("password");
        if (username == null || password == null) {
            return Result.error("用户名或密码为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<User> lu = userMapper.selectList(queryWrapper);
        if (lu.isEmpty()) {
            return Result.error("用户不存在");
        }

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(data.get("username"), data.get("password"));
        // 这里登录失败会自动处理
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();
        String jwt = JwtUtil.createJWT(user.getId().toString());
        Map<String, String> res = new HashMap<>();
        res.put("token", jwt);
        return Result.ok("success", res);
    }

    @Override
    public Result register(Map<String, String> data) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String username = data.get("username");
        String password = data.get("password");
        String confirmedPassword = data.get("confirmedPassword");

        if (username == null || password == null || confirmedPassword == null) {
            return Result.error("用户名或密码为空");
        }
        if (username.length() < 5 || username.length() > 15) {
            return Result.error("用户名过短或过长");
        }
        username = username.trim();
        if (username.length() < 5 || username.length() > 15) {
            return Result.error("用户名过短或过长");
        }
        if (password.length() < 8 || password.length() > 20) {
            return Result.error("密码过短或过长");
        }
        if (!password.equals(confirmedPassword)) {
            return Result.error("两次输入的密码不一致");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        if (!userMapper.selectList(userQueryWrapper).isEmpty()) {
            return Result.error("用户名已存在");
        }

        userMapper.insert(new User(null, username, passwordEncoder.encode(password)));
        // 创建user对应的userinfo
        QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
        userQueryWrapper1.eq("username", username);
        User user = userMapper.selectOne(userQueryWrapper1);
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("uid", user.getId()));
        if (userInfo == null) {
            userInfoMapper.insert(new UserInfo(null, user.getId(), "", "", "", null, null));
        }
        return Result.ok("success");
    }

    @Override
    public Result getInfo() {
        User curUser = IdentityAuthenticationUtil.getCurUser();
        Map<String, String> res = new HashMap<>();
        res.put("id", curUser.getId().toString());
        res.put("username", curUser.getUsername());

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("uid", curUser.getId());
        UserInfo userInfo = userInfoMapper.selectOne(userInfoQueryWrapper);
        if (userInfo == null) {
            return Result.ok("success", res);
        }
        res.put("name", userInfo.getName());
        res.put("phoneNumber", userInfo.getPhoneNumber());
        res.put("idNum", userInfo.getIdNum());
        res.put("userInfoId", userInfo.getId().toString());

        return Result.ok("success", res);
    }

    @Override
    public Result updatePassword(Map<String, String> data) {
        User curUser = IdentityAuthenticationUtil.getCurUser();
        try {
            PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String oldPassword = data.get("oldPassword");
            String newPassword = data.get("newPassword");
            String confirmedNewPassword = data.get("confirmedNewPassword");
            if (!passwordEncoder.matches(oldPassword, curUser.getPassword())) {
                return Result.error("旧密码有误");
            }

            if (newPassword == null || newPassword.length() == 0 ||  newPassword.length() < 8 || newPassword.length() > 20) {
                return Result.error("新密码过长或过短");
            }
            if (oldPassword.equals(newPassword)) {
                return Result.error("新旧密码不能一致");
            }
            if (!newPassword.equals(confirmedNewPassword)) {
                return Result.error("两次密码不一致");
            }
            curUser.setPassword(passwordEncoder.encode(newPassword));
            userMapper.updateById(curUser);
            return Result.ok("update success");
        } catch (Exception e) {
            return Result.error("数据有误");
        }
    }


}
